<?php

define('SITE_DIR',dirname(__FILE__) . '/..');
require_once dirname(__FILE__) . '/../../projects/bazalt/framework/core/include.inc';

using('Framework.System.Config');
using('Framework.System.Error');
Error::setFormat(Error::ConsoleFormat);

using('Framework.System.Orm');

require_once  'include.inc';

class Main
{
    private static $config;
    private static $logger;
    private static $daemonName;
    private static $daemonList;

    public static function loadConfig()
    {
        self::$config = WebConfigReader::load( 'web.config');
    }

    public static function start()
    {        
        self::loadConfig();
        self::initParams();
        
        self::$logger = Logger::getLogger( self::$daemonName );
        
        self::checkParams();
 
        try {
        
            $obj = new self::$daemonName();
            $obj->work();
            
        } catch (Exception $exception) {
            die( "\n" . $exception->getMessage() . "\n" );
        }
    }
    
    protected function initParams()
    {
        $params = $_SERVER['argv'];
        
        if(substr($params[1] ,0,2)=='-n') {
            self::$daemonName = substr( $params[1], 3, strlen($params[1]) );
        } else {
            die( 'Daemon name is not set. Please use -n key (-n=Some_Daemon)' );
        } 
    }
    
    protected function checkParams()
    {
        if( !self::daemonExists() ) {
           die( 'Daemon '.self::$daemonName.' not found' );
        }
    }
    
    protected function daemonExists()
    {
        if(is_null(self::$daemonName)) {
            return false;
        }
        
        if( is_null(self::$daemonList) ) {
            self::$daemonList = array();
            $classes = get_declared_classes();
            foreach ($classes as $class) {
                if (typeOf($class)->isSubclassOf('DaemonAbstract')) {
                    self::$daemonList[] = $class;
                }
            }
        }

        return in_array(self::$daemonName,self::$daemonList);
    }    
}

Main::start();